package com.huajx.core.handler;

import com.huajx.core.Hboot;
import com.huajx.core.config.HbootConfig;
import com.huajx.util.HexUtil;
import com.huajx.util.StrUtil;
import com.huajx.util.lang.Assert;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @program: di-parent
 * @description:
 * @author: lisa 叶新华
 * @create: 2020-03-26 09:42
 */
public abstract class AbstractHandler implements HandlerAdapter {
    protected final static Logger logger = LoggerFactory.getLogger(AbstractHandler.class);
    protected final static String SERVER_URL = Hboot.config(HbootConfig.class).getRemoteUrl();

    protected final static String[] serverUrls = getServerUrls();
    private static int serverUrlIndex = 0;

    /**
     * 响应数据包前缀
     *
     * @return 响应数据包前缀
     */
    protected abstract String getReturnPrefix();

    protected abstract <T> T getMessage(Object msg);

    /**
     * 从配置文件中获取服务器请求URLs,
     * 数组表示是集群，在配置文件中，以逗号分隔
     *
     * @return 服务器请求URLs
     */
    private static String[] getServerUrls() {
        if (StrUtil.isNotBlank(SERVER_URL)) {
            return SERVER_URL.split(",");
        }
        return new String[0];
    }

    private boolean isHttpUrl(String url) {
        return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("//");
    }

    /**
     * 获取远程访问URL
     *
     * @param url 服务器路径
     * @return 服务URL
     */
    protected String getServerUrl(String url) {

        if (isHttpUrl(url)) {
            return url;
        }

        int len = serverUrls.length;

        if (serverUrlIndex >= len) {
            serverUrlIndex = 0;
        }

        String surl = serverUrls[serverUrlIndex];

//        logger.info("当前请求URL:{}， 第{}", surl, serverUrlIndex);

        serverUrlIndex++;

        if (StrUtil.isBlank(url)) {
            return surl;
        } else {
            return surl + url;
        }
    }

    /**
     * 空响应
     *
     * @param session 会话
     */
    @Override
    public void render(IoSession session) {

    }

    protected void printMessage(Object msg) {
        Assert.notNull(msg);

        if (msg instanceof byte[]) {
            logger.info(HexUtil.encodeHexStr((byte[])msg));
        }
    }
}
